//
//  ZSTagButtonView.m
//  Fangxiaov
//
//  Created by safiri on 2017/3/3.
//  Copyright © 2017年 com.f. All rights reserved.
//

#import "ZSTagButtonView.h"

@interface ZSTagButtonView ()
@property (nonatomic ,strong ,nullable) NSMutableArray *tags;
@property (nonatomic ,assign) BOOL didSetup;
@property (nonatomic ,assign) BOOL outOfBounds;
@end

@implementation ZSTagButtonView

/**
 重写了UIView 中的 -(CGSize)intrinsicContentSize: 方法计算自己的大小
 在需要改变这个值的时候调用：invalidateIntrinsicContentSize 方法，通知系统这个值改变了。
 @return 大小
 */
- (CGSize)intrinsicContentSize {
    if (!self.tags.count) {
        return CGSizeZero;
    }
    
    NSArray *subviews = self.subviews;
    UIView *previousView = nil;
    CGFloat topPadding = self.padding.top;
    CGFloat bottomPadding = self.padding.bottom;
    CGFloat leftPadding = self.padding.left;
    CGFloat rightPadding = self.padding.right;
    CGFloat itemSpacing = self.itemSpacing;
    CGFloat lineSpacing = self.lineSpacing;
    CGFloat currentX = leftPadding;
    CGFloat intrinsicHeight = topPadding;
    CGFloat intrinsicWidth = leftPadding;
    
    if (!self.singleLine && self.preferredMaxLayoutWidth > 0) {
        NSInteger lineCount = 0;
        for (UIView *view in subviews) {
            CGSize size = view.intrinsicContentSize;
            if (previousView) {
                CGFloat width = size.width;
                currentX += itemSpacing;
                if (currentX + width + rightPadding <= self.preferredMaxLayoutWidth) {
                    currentX += size.width;
                } else {
                    lineCount ++;
                    currentX = leftPadding + size.width;
                    intrinsicHeight += size.height;
                }
            } else {
                lineCount ++;
                intrinsicHeight += size.height;
                currentX += size.width;
            }
            previousView = view;
            intrinsicWidth = MAX(intrinsicWidth, currentX + rightPadding);
        }
        self.lines = lineCount;
        if (self.commitLines) {
            self.commitLines(self.lines);
        }
        intrinsicHeight += bottomPadding + lineSpacing * (lineCount - 1);
    } else {
        for (UIView *view in subviews) {
            CGSize size = view.intrinsicContentSize;
            intrinsicWidth += size.width;
        }
        intrinsicWidth += itemSpacing * (subviews.count - 1) + rightPadding;
        intrinsicHeight += ((UIView *)subviews.firstObject).intrinsicContentSize.height + bottomPadding;
    }
    
    return CGSizeMake(intrinsicWidth, intrinsicHeight);
}
- (void)layoutSubviews {
    //不固定宽度，可放在scrollView中实现单行滑动？
//    if (!self.singleLine) {
//        self.preferredMaxLayoutWidth = self.frame.size.width;
//    }
    //固定宽度的一行
    self.preferredMaxLayoutWidth = self.frame.size.width;
    [super layoutSubviews];
    
    [self layoutTags];
}
#pragma mark - Private

- (void)layoutTags {
    if (self.didSetup || !self.tags.count) {
        return;
    }
    
    NSArray *subviews = self.subviews;
    UIView *previousView = nil;
    CGFloat topPadding = self.padding.top;
    CGFloat leftPadding = self.padding.left;
    CGFloat rightPadding = self.padding.right;
    CGFloat bottomPadding = self.padding.bottom;
    CGFloat itemSpacing = self.itemSpacing;
    CGFloat lineSpacing = self.lineSpacing;
    CGFloat currentX = leftPadding;
    
    if (!self.singleLine && self.preferredMaxLayoutWidth > 0) {
        if (self.outOfBounds) return;
        for (UIView *view in subviews) {
            CGSize size = view.intrinsicContentSize;
            if (previousView) {
                CGFloat width = size.width;
                currentX += itemSpacing;
                if (currentX + width + rightPadding <= self.preferredMaxLayoutWidth) {
                    if (CGRectGetMaxY(previousView.frame) + lineSpacing <= self.bounds.size.height - bottomPadding) {
                        view.frame = CGRectMake(currentX, CGRectGetMinY(previousView.frame), size.width, size.height);
                        currentX += size.width;
                    }else{
                        [view removeFromSuperview];
                        self.outOfBounds = YES;
                        break;
                    }
                    
                } else {
                    CGFloat width = MIN(size.width, self.preferredMaxLayoutWidth - leftPadding - rightPadding);
                    if (CGRectGetMaxY(previousView.frame) + lineSpacing < self.bounds.size.height - bottomPadding) {
                        view.frame = CGRectMake(leftPadding, CGRectGetMaxY(previousView.frame) + lineSpacing, width, size.height);
                        currentX = leftPadding + width;
                    }else{
                        [view removeFromSuperview];
                        self.outOfBounds = YES;
                        break;
                    }
                }
            } else {
                CGFloat width = MIN(size.width, self.preferredMaxLayoutWidth - leftPadding - rightPadding);
                view.frame = CGRectMake(leftPadding, topPadding, width, size.height);
                currentX += width;
            }
            
            previousView = view;
        }
    } else {
        for (UIView *view in subviews) {
            CGSize size = view.intrinsicContentSize;
            view.frame = CGRectMake(currentX, topPadding, size.width, size.height);
            currentX += size.width;
            currentX += itemSpacing;
            if (currentX + rightPadding > self.preferredMaxLayoutWidth) {
                [view removeFromSuperview];
                self.outOfBounds = YES;
                break;
            }
            previousView = view;
        }
    }
    
    //NSLog(@"%@",NSStringFromCGRect(previousView.frame));
    
    self.didSetup = YES;
}
//MARK: 点击事件
- (void)onTag: (UIButton *)btn {
    btn.selected = !btn.selected;
    if (self.didTapTagAtIndex) {
        self.didTapTagAtIndex([self.subviews indexOfObject: btn]);
    }
}
#pragma mark - getter setter

- (NSMutableArray *)tags {
    if(!_tags) {
        _tags = [NSMutableArray array];
    }
    return _tags;
}

- (void)setPreferredMaxLayoutWidth: (CGFloat)preferredMaxLayoutWidth {
    if (preferredMaxLayoutWidth != _preferredMaxLayoutWidth) {
        _preferredMaxLayoutWidth = preferredMaxLayoutWidth;
        _didSetup = NO;
        [self invalidateIntrinsicContentSize];
    }
}


#pragma mark - Public

- (void)addTag:(ZSButtonTag *)tag {
    if (self.outOfBounds) return;
    
    NSParameterAssert(tag);
    ZSTagButton *btn = [ZSTagButton buttonWithTag:tag];
    [btn addTarget:self action:@selector(onTag:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:btn];
    [self.tags addObject:tag];
    
    self.didSetup = NO;
    [self invalidateIntrinsicContentSize];
}
- (void)addTagTitles:(nonnull NSArray *)tagTitleArray withSameTag:(nonnull ZSButtonTag *)sameTag {
    for (NSString *title in tagTitleArray) {
        ZSButtonTag *tag = [[ZSButtonTag alloc] initWithSameTag:sameTag];
        tag.text = title;
        [self addTag:tag];
    }
}
- (void)insertTag:(ZSButtonTag *)tag atIndex:(NSUInteger)index {
    if(self.outOfBounds) return;
    NSParameterAssert(tag);
    if (index + 1 > self.tags.count) {
        [self addTag: tag];
    } else {
        ZSTagButton *btn = [ZSTagButton buttonWithTag:tag];
        [btn addTarget:self action:@selector(onTag:) forControlEvents:UIControlEventTouchUpInside];
        [self insertSubview:btn atIndex:index];
        [self.tags insertObject:tag atIndex:index];
        
        self.didSetup = NO;
        [self invalidateIntrinsicContentSize];
    }
}

- (void)removeTag:(ZSButtonTag *)tag {
    NSParameterAssert(tag);
    NSUInteger index = [self.tags indexOfObject:tag];
    if (NSNotFound == index) {
        return;
    }
    
    [self.tags removeObjectAtIndex:index];
    if (self.subviews.count > index) {
        [self.subviews[index] removeFromSuperview];
        self.outOfBounds = NO;
    }
    
    self.didSetup = NO;
    [self invalidateIntrinsicContentSize];
}

- (void)removeTagAtIndex:(NSUInteger)index {
    if (index + 1 > self.tags.count) {
        return;
    }
    
    [self.tags removeObjectAtIndex:index];
    if (self.subviews.count > index) {
        [self.subviews[index] removeFromSuperview];
    }
    
    self.didSetup = NO;
    [self invalidateIntrinsicContentSize];
}

- (void)removeAllTags {
    [self.tags removeAllObjects];
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
    
    self.didSetup = NO;
    [self invalidateIntrinsicContentSize];
}


@end
